package com.centaline.androidsalesblog.activities.newest;

import android.content.Intent;
import android.support.design.widget.TextInputLayout;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;

import com.android.volley.VolleyError;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.activities.entrust.ModifyPhoneActivity;
import com.centaline.androidsalesblog.activities.mine.BindingPhoneActivity;
import com.centaline.androidsalesblog.activities.mine.LoginActivity;
import com.centaline.androidsalesblog.api.usercenter.InsertBookApi;
import com.centaline.androidsalesblog.base.BaseActivity;
import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.constants.CommonConstant;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.model.databaseobject.NewEstActDo;
import com.centaline.androidsalesblog.model.databaseobject.UserDo;
import com.centaline.androidsalesblog.model.responseobject.InsertBookRo;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centanet.framework.interfaces.IResponseListener;
import com.jakewharton.rxbinding.view.RxView;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.trello.rxlifecycle.ActivityEvent;

import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func2;
import rx.schedulers.Schedulers;

/**
 * 新盘活动报名
 * Created by guilin on 16/4/15.
 */
public class NewPropActBookActivity extends BaseActivity {

    private TextInputLayout til_name;
    private AppCompatTextView atv_mobile;
    private Button btn_confirm;
    private EditText nameEditText;

    private NewEstActDo newEstActDo;
    private String userPhone;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_newpropactbook;
    }

    @Override
    protected void findViews() {
        setUniversalToolbar(R.string.title_new_est_act_book);
        til_name = (TextInputLayout) findViewById(R.id.til_name);
        atv_mobile = (AppCompatTextView) findViewById(R.id.atv_mobile);
        btn_confirm = (Button) findViewById(R.id.btn_confirm);
    }

    @Override
    protected void initViews() {
        nameEditText = til_name.getEditText();
        if (nameEditText != null) {
            Observable<CharSequence> nameChangeObservable = RxTextView.textChanges(nameEditText);
            Observable<CharSequence> phoneChangeObservable = RxTextView.textChanges(atv_mobile);
            nameChangeObservable.
                    compose(this.<CharSequence>bindUntilEvent(ActivityEvent.DESTROY))
                    .subscribe(new Action1<CharSequence>() {
                        @Override
                        public void call(CharSequence charSequence) {
                            if (charSequence.length() > 0) {
                                til_name.setError(null);
                            } else if (til_name.getError() == null) {
                                til_name.setError(getString(R.string.hint_input_name));
                            }
                        }
                    });

            phoneChangeObservable.
                    compose(this.<CharSequence>bindUntilEvent(ActivityEvent.DESTROY))
                    .subscribe(new Action1<CharSequence>() {
                        @Override
                        public void call(CharSequence charSequence) {
//                            atv_mobile.setEnabled(charSequence.length() != 11);
                        }
                    });

            Observable.combineLatest(nameChangeObservable, phoneChangeObservable,
                    new Func2<CharSequence, CharSequence, Boolean>() {
                        @Override
                        public Boolean call(CharSequence name, CharSequence mobile) {
                            boolean nameValid = mobile.length() == 11 &&
                                    "1".equals(String.valueOf(mobile.charAt(0)));
                            boolean mobileValid = name.length() > 0;
                            return nameValid && mobileValid;
                        }
                    })
                    .compose(this.<Boolean>bindUntilEvent(ActivityEvent.DESTROY))
                    .subscribe(new Action1<Boolean>() {
                        @Override
                        public void call(Boolean aBoolean) {
                            btn_confirm.setEnabled(aBoolean);
                        }
                    });
        }

        RxView.clicks(atv_mobile)
                .throttleFirst(1, TimeUnit.SECONDS)
                .compose(this.<Void>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        if (AppConstant.IsLogin) {
                            if (TextUtils.isEmpty(userPhone)) {
                                startActivityForResult(new Intent(NewPropActBookActivity.this, BindingPhoneActivity.class),
                                        CommonConstant.REQ_BIND_MOBILE);
                            } else {
                                startActivityForResult(new Intent(NewPropActBookActivity.this, ModifyPhoneActivity.class), CommonConstant.REQ_MODIFY_MOBILE);
                            }
                        } else {
                            startActivityForResult(new Intent(NewPropActBookActivity.this, BindingPhoneActivity.class),
                                    CommonConstant.REQ_BIND_MOBILE);
                        }
                    }
                });

        RxView.clicks(btn_confirm)
                .throttleFirst(1, TimeUnit.SECONDS)
                .compose(this.<Void>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        request();
                    }
                });
        newEstActDo = getIntent().getParcelableExtra(ExtraConstant.NewEstActObject);
        checkLogin();
    }

    private void checkLogin() {
        if (AppConstant.IsLogin) {
            userInfo();
        } else {
            startActivityForResult(new Intent(this, LoginActivity.class), CommonConstant.REQ_LOGIN);
        }
    }

    private void request() {
        hideKeyboard(atv_mobile);
        InsertBookApi insertBookApi = new InsertBookApi(NewPropActBookActivity.class, InsertBookRo.class,
                new IResponseListener<InsertBookRo>() {
                    @Override
                    public void onResponse(InsertBookRo insertBookRo) {
                        if (insertBookRo.getResultNo() == 0) {
                            toast("报名成功");
                            setResult(RESULT_OK);
                            finish();
                        } else {
                            cancelLoadingDialog();
                            snack(insertBookRo.getMessage());
                        }
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        netWorkUnable();
                    }
                });
        insertBookApi.setActId(newEstActDo.getActId());
        insertBookApi.setEstId(newEstActDo.getEstId());
        insertBookApi.setEstExtId(newEstActDo.getEstExtId());
        insertBookApi.setCustomerName(nameEditText.getText().toString());
        insertBookApi.setCustomerMobile(atv_mobile.getText().toString());
        insertBookApi.startRequest();
        showLoadingDialog();
    }

    /**
     * 用户信息
     */
    private void userInfo() {
        RxDataBase.getUser()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<UserDo>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<UserDo>() {
                    @Override
                    public void call(UserDo userDo) {
                        if (userDo != null) {
                            userPhone = userDo.getPhone();
                            atv_mobile.setText(TextUtils.isEmpty(userDo.getPhone()) ?
                                    getString(R.string.hint_book_mobile) :
                                    userDo.getPhone());
                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RESULT_OK == resultCode) {
            switch (requestCode) {
                case CommonConstant.REQ_LOGIN:
                case CommonConstant.REQ_BIND_MOBILE:
                    userInfo();
                    break;
                case CommonConstant.REQ_MODIFY_MOBILE:
                    atv_mobile.setText(data.getStringExtra(ExtraConstant.Phone));
                    break;
                default:
                    break;
            }
        } else if (CommonConstant.REQ_LOGIN == requestCode) {
            finish();
        }
    }
}
